package io.andronicus.simplifiedrecyclerview;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;

import java.util.List;

/**
 * MyAdapter.
 */
public class MyAdapter<T> extends BaseItemProvider {
    private int mLayoutResId;
    private List<T> mData;
    private ViewHolderCallbacks<T> mHandler;
    private Component mView;
    private Context mContext;

    public MyAdapter(int layoutResId, List<T> data, Context context, ViewHolderCallbacks<T> handler) {
        this.mLayoutResId = layoutResId;
        this.mData = data;
        this.mContext = context;
        this.mHandler = handler;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    /**
     * setData.
     *
     * @param data list
     */
    public void setData(List<T> data) {
        this.mData = data;
        notifyDataChanged();
    }

    /**
     * getItemAtPosition.
     *
     * @param position integer
     * @return T
     */
    public T getItemAtPosition(int position) {
        return this.mData.get(position);
    }

    /**
     * getAllItems.
     *
     * @return T
     */
    public List<T> getAllItems() {
        return this.mData;
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * ViewHolderCallbacks.
     */
    public interface ViewHolderCallbacks<T> {
        void onViewHolderClick(T item, int position);

        void onViewHolderLongClick(T item, int position);

        void bindDataToViews(T item, Component view);
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        Component rootView = LayoutScatter.getInstance(mContext)
                .parse(mLayoutResId, componentContainer, false);
        mView = rootView;
        mHandler.bindDataToViews(mData.get(position), mView);
        return mView;
    }
}
